package com.um.springcloud.dubbo.event;

import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository;
import com.alibaba.cloud.dubbo.registry.event.ServiceInstancesChangedEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Set;


/**
 * 应用启动完成主动探测订阅的服务
 *
 * @author 甘天伟
 * @since 2022/8/22
 * 版权所有 广州优匠科技有限公司
 */
@Slf4j
@Component
public class DubboActiveProbeListener implements ApplicationListener<ApplicationReadyEvent> {

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        DubboServiceMetadataRepository dubboServiceMetadataRepository = event.getApplicationContext().getBean(DubboServiceMetadataRepository.class);
        Set<String> subscribedServices = dubboServiceMetadataRepository.getSubscribedServices();
        if (!ObjectUtils.isEmpty(subscribedServices)) {
            DiscoveryClient DiscoveryClient = event.getApplicationContext().getBean(DiscoveryClient.class);
            for (String subscribedService : subscribedServices) {
                log.info("Active probe service: {}", subscribedService);
                ServiceInstancesChangedEvent changedEvent = new ServiceInstancesChangedEvent(subscribedService, DiscoveryClient.getInstances(subscribedService));
                event.getApplicationContext().publishEvent(changedEvent);
            }
        }
    }

}
